class PodcastGenerator {
    constructor() {
        this.tasks = new Map();
        this.init();
    }

    init() {
        const form = document.getElementById('podcastForm');
        form.addEventListener('submit', (e) => this.handleSubmit(e));
    }

    async handleSubmit(e) {
        e.preventDefault();
        
        const topic = document.getElementById('topic').value;
        const mode = document.querySelector('input[name="mode"]:checked').value;
        
        if (!topic.trim()) {
            alert('请输入播客主题');
            return;
        }
        
        try {
            // 发送生成请求
            const response = await fetch('/generate', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ topic, mode })
            });
            
            const data = await response.json();
            
            if (response.ok) {
                // 添加新任务到界面
                this.addTask(data.task_id, topic);
                
                // 开始轮询任务进度
                this.startPolling(data.task_id);
                
                // 清空输入框
                document.getElementById('topic').value = '';
                
                // 隐藏"暂无任务"消息
                document.getElementById('noTasksMessage').style.display = 'none';
            } else {
                alert('生成失败: ' + data.error);
            }
        } catch (error) {
            console.error('Error:', error);
            alert('请求失败，请重试');
        }
    }
    
    addTask(taskId, topic) {
        const container = document.getElementById('tasksContainer');
        const taskElement = document.createElement('div');
        taskElement.className = 'task-card card';
        taskElement.id = `task-${taskId}`;
        taskElement.innerHTML = `
            <div class="card-body">
                <div class="task-header">
                    <h6 class="task-title">任务: ${topic}</h6>
                    <div class="task-actions">
                        <span class="status-badge badge bg-secondary">已开始</span>
                        <button class="btn btn-sm btn-outline-danger delete-btn" data-task-id="${taskId}">删除</button>
                    </div>
                </div>
                <div class="mt-2">
                    <div class="d-flex justify-content-between">
                        <small>进度:</small>
                        <small class="progress-text">0%</small>
                    </div>
                    <div class="progress mt-1">
                        <div class="progress-bar" role="progressbar" style="width: 0%"></div>
                    </div>
                </div>
                <div class="result-section" style="display: none;">
                    <h6>生成结果</h6>
                    <div class="result-text"></div>
                    <div class="audio-players"></div>
                </div>
            </div>
        `;
        
        container.prepend(taskElement);
        
        // 添加删除按钮事件
        const deleteBtn = taskElement.querySelector('.delete-btn');
        deleteBtn.addEventListener('click', () => this.deleteTask(taskId));
        
        // 存储任务引用
        this.tasks.set(taskId, {
            element: taskElement,
            polling: true
        });
    }
    
    async startPolling(taskId) {
        const poll = async () => {
            if (!this.tasks.has(taskId) || !this.tasks.get(taskId).polling) {
                return;
            }
            
            try {
                const response = await fetch(`/progress/${taskId}`);
                const data = await response.json();
                
                if (response.ok) {
                    this.updateTaskProgress(taskId, data);
                    
                    if (data.status === 'completed' || data.status === 'failed') {
                        // 停止轮询
                        if (this.tasks.has(taskId)) {
                            this.tasks.get(taskId).polling = false;
                        }
                    } else {
                        // 继续轮询
                        setTimeout(poll, 2000);
                    }
                } else {
                    console.error('获取进度失败:', data.error);
                    // 停止轮询
                    if (this.tasks.has(taskId)) {
                        this.tasks.get(taskId).polling = false;
                    }
                }
            } catch (error) {
                console.error('轮询错误:', error);
                // 继续轮询
                setTimeout(poll, 5000);
            }
        };
        
        // 开始轮询
        poll();
    }
    
    updateTaskProgress(taskId, data) {
        const taskElement = document.getElementById(`task-${taskId}`);
        if (!taskElement) return;
        
        // 更新状态标签
        const statusBadge = taskElement.querySelector('.status-badge');
        switch (data.status) {
            case 'started':
                statusBadge.className = 'status-badge badge bg-secondary';
                statusBadge.textContent = '已开始';
                break;
            case 'generating_text':
                statusBadge.className = 'status-badge badge bg-warning text-dark';
                statusBadge.textContent = '生成文本中';
                break;
            case 'completed':
                statusBadge.className = 'status-badge badge bg-success';
                statusBadge.textContent = '已完成';
                break;
            case 'failed':
                statusBadge.className = 'status-badge badge bg-danger';
                statusBadge.textContent = '失败';
                break;
            default:
                statusBadge.className = 'status-badge badge bg-secondary';
                statusBadge.textContent = data.status;
        }
        
        // 更新进度条
        const progressBar = taskElement.querySelector('.progress-bar');
        const progressText = taskElement.querySelector('.progress-text');
        progressBar.style.width = `${data.progress}%`;
        progressText.textContent = `${data.progress}%`;
        
        // 如果已完成，显示结果
        if (data.status === 'completed' || data.status === 'failed') {
            const resultSection = taskElement.querySelector('.result-section');
            resultSection.style.display = 'block';
            
            const resultText = taskElement.querySelector('.result-text');
            resultText.innerHTML = `<p>${data.result_text}</p>`;
            
            // 显示音频播放器
            if (data.result_audio_files && data.result_audio_files.length > 0) {
                const audioPlayers = taskElement.querySelector('.audio-players');
                audioPlayers.innerHTML = '<h6>音频播放</h6>';
                
                data.result_audio_files.forEach((filename, index) => {
                    const audioElement = document.createElement('div');
                    audioElement.className = 'mb-2';
                    audioElement.innerHTML = `
                        <small>音频片段 ${index + 1}:</small>
                        <audio class="audio-player" controls>
                            <source src="/audio/${filename}" type="audio/mpeg">
                            您的浏览器不支持音频播放。
                        </audio>
                    `;
                    audioPlayers.appendChild(audioElement);
                });
            }
        }
    }
    
    deleteTask(taskId) {
        // 停止轮询
        if (this.tasks.has(taskId)) {
            this.tasks.get(taskId).polling = false;
            this.tasks.delete(taskId);
        }
        
        // 从DOM中移除
        const taskElement = document.getElementById(`task-${taskId}`);
        if (taskElement) {
            taskElement.remove();
        }
        
        // 如果没有任务了，显示提示信息
        if (this.tasks.size === 0) {
            const taskElements = document.querySelectorAll('.task-card');
            if (taskElements.length === 0) {
                document.getElementById('noTasksMessage').style.display = 'block';
            }
        }
    }
}

// 初始化应用
document.addEventListener('DOMContentLoaded', () => {
    new PodcastGenerator();
});